/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package validators;

import interfaces.UserProjectInterface;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Thibault
 */
@FacesValidator("emailValidator")
public class EmailValidator implements Validator {

    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\."
            + "[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*"
            + "(\\.[A-Za-z]{2,})$";
    private Pattern pattern;
    private Matcher matcher;

    public EmailValidator() {
        pattern = Pattern.compile(EMAIL_PATTERN);
    }

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

        String enteredEmail = (String) value;

        //Check mail format
        matcher = pattern.matcher(enteredEmail.toString());
        if (!matcher.matches()) {

            FacesMessage msg =
                    new FacesMessage("Invalid E-mail format.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);

        }

        //Check that the mail is not already in use
        UserProjectInterface userEJB = null;
        //Can't use injection in validator (wait for jsf 2.2)
        try {
            userEJB = (UserProjectInterface) new InitialContext().lookup("java:global/Project-war/UserProjectManager");
        } catch (NamingException ne) {
            System.out.println("EmailValidator : validate :: Erreur de lookup pour l'EJB UserProjectInterface");
        }
        if (userEJB.isMailAlreadyUsed(enteredEmail)) {
            FacesMessage msg = new FacesMessage("Email already in use.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }
    }
}
